package edu.hawaii.duedates.mail;

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * Contains an email constructor.
 * 
 * @author Arthur Shum and Erin Kim
 * 
 */
public class Email {

  /**
   * An email constructor which sends out an email given the email address destination, smtp host,
   * and a message.
   * 
   * @param emailAddr the email address destination
   * @param smtpHost the SMTP host of the user
   * @param emailBody the message
   * @throws Exception If an error occurs while trying to send the email
   */
  public Email(String emailAddr, String smtpHost, String emailBody) throws Exception {
    Properties props = System.getProperties();  
    props.put("mail.smtp.host", smtpHost);
    Session session = Session.getInstance(props);
    Message msg = new MimeMessage(session);
    try {
      InternetAddress fromAddr = new InternetAddress("duedates-blue@hawaii.edu");
      InternetAddress toAddr = new InternetAddress(emailAddr, true);
      msg.setFrom(fromAddr);
      msg.setRecipient(Message.RecipientType.TO, toAddr);
      msg.setSentDate(new Date());
      msg.setSubject("DueDates!");
      msg.setText(emailBody);
      Transport.send(msg);
    }
    catch (AddressException a) {
      throw new Exception ("Email address error.", a);
    }
    catch (MessagingException m) {
      throw new Exception ("Error sending message.", m);
    }
  }

}
